/**
 * 工作人员管理脚本
 */

// 全局变量
let currentPage = 1;
let pageSize = 10;
let currentRoleFilter = '';
let siteList = [];

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态和权限
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    if (!Auth.checkRole(UserRole.SUPER_ADMIN)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    initPage();
});

/**
 * 初始化页面
 */
async function initPage() {
    // 显示用户信息
    displayUserInfo();
    
    // 加载接种点列表（用于下拉框）
    await loadSiteListForSelect();
    
    // 加载工作人员列表
    await loadStaffList();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = document.getElementById('userName');
        const userAvatar = document.getElementById('userAvatar');
        
        if (userName) userName.textContent = userInfo.account || '超级管理员';
        if (userAvatar) userAvatar.textContent = (userInfo.account || 'S').charAt(0).toUpperCase();
    }
}

/**
 * 加载接种点列表（用于下拉框）
 */
async function loadSiteListForSelect() {
    try {
        // 后端返回的是数组，不是分页对象
        const sites = await HttpClient.get('/admin/vaccination-site/list');
        siteList = sites || [];
        
        // 填充接种点下拉框
        const siteSelect = document.getElementById('staffSiteId');
        siteSelect.innerHTML = '<option value="">请选择</option>' + 
            siteList.map(site => `<option value="${site.id}">${site.name}</option>`).join('');
    } catch (error) {
        console.error('加载接种点列表失败:', error);
        UI.showMessage('加载接种点列表失败: ' + error.message, 'danger');
    }
}

/**
 * 加载工作人员列表
 */
async function loadStaffList() {
    try {
        UI.showLoading();
        
        let url = `/admin/user/list?pageNum=${currentPage}&pageSize=${pageSize}`;
        if (currentRoleFilter) {
            url += `&identityInfo=${currentRoleFilter}`;
        }
        
        const data = await HttpClient.get(url);
        
        displayStaffList(data.records || []);
        displayPagination(data);
        
        UI.hideLoading();
    } catch (error) {
        console.error('加载工作人员列表失败:', error);
        UI.hideLoading();
        UI.showMessage('加载数据失败: ' + error.message, 'danger');
    }
}

/**
 * 显示工作人员列表
 */
function displayStaffList(staffList) {
    const tbody = document.getElementById('staffTableBody');
    
    if (!staffList || staffList.length === 0) {
        tbody.innerHTML = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
        return;
    }
    
    tbody.innerHTML = staffList.map(staff => {
        const siteName = staff.vaccinationSiteId ? 
            (siteList.find(s => s.id === staff.vaccinationSiteId)?.name || '-') : '-';
        
        return `
            <tr>
                <td>${staff.userId}</td>
                <td>${staff.account || '-'}</td>
                <td>${staff.name || '-'}</td>
                <td>${staff.age || '-'}</td>
                <td>${staff.idNum || '-'}</td>
                <td>${staff.email || '-'}</td>
                <td>${Format.userRole(staff.identityInfo)}</td>
                <td>${siteName}</td>
                <td>
                    <button class="btn btn-sm btn-warning" onclick="showResetPasswordModal(${staff.userId}, '${staff.account}')">
                        <i class="fas fa-key"></i> 重置密码
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="handleDelete(${staff.userId}, '${staff.account}')">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            </tr>
        `;
    }).join('');
}

/**
 * 显示分页
 */
function displayPagination(data) {
    const pagination = document.getElementById('pagination');
    const totalPages = data.pages || 1;
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = '<div class="pagination-container">';
    
    // 上一页
    html += `<button class="pagination-btn" ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">上一页</button>`;
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            html += `<button class="pagination-btn ${i === currentPage ? 'active' : ''}" onclick="changePage(${i})">${i}</button>`;
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            html += '<span class="pagination-ellipsis">...</span>';
        }
    }
    
    // 下一页
    html += `<button class="pagination-btn" ${currentPage === totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">下一页</button>`;
    
    html += '</div>';
    pagination.innerHTML = html;
}

/**
 * 切换页码
 */
async function changePage(page) {
    currentPage = page;
    await loadStaffList();
}

/**
 * 处理筛选条件变化
 */
async function handleFilterChange() {
    currentRoleFilter = document.getElementById('roleFilter').value;
    currentPage = 1;
    await loadStaffList();
}

/**
 * 显示添加模态框
 */
function showAddModal() {
    document.getElementById('staffForm').reset();
    document.getElementById('siteSelectGroup').style.display = 'none';
    document.getElementById('staffModal').classList.add('show');
}

/**
 * 关闭模态框
 */
function closeModal() {
    document.getElementById('staffModal').classList.remove('show');
    document.getElementById('staffForm').reset();
}

/**
 * 处理角色变化
 */
function handleRoleChange() {
    const role = document.getElementById('staffRole').value;
    const siteSelectGroup = document.getElementById('siteSelectGroup');
    const staffSiteId = document.getElementById('staffSiteId');
    
    if (role === '1') {
        // 接种点管理员需要选择接种点
        siteSelectGroup.style.display = 'block';
        staffSiteId.required = true;
    } else {
        // 超级管理员不需要选择接种点
        siteSelectGroup.style.display = 'none';
        staffSiteId.required = false;
        staffSiteId.value = '';
    }
}

/**
 * 处理表单提交
 */
async function handleSubmit() {
    const form = document.getElementById('staffForm');
    
    // 表单验证
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const role = parseInt(document.getElementById('staffRole').value);
    const siteId = document.getElementById('staffSiteId').value;
    
    // 如果是接种点管理员，必须选择接种点
    if (role === 1 && !siteId) {
        UI.showMessage('请选择所属接种点', 'warning');
        return;
    }
    
    const data = {
        account: document.getElementById('staffAccount').value.trim(),
        password: document.getElementById('staffPassword').value.trim(),
        email: document.getElementById('staffEmail').value.trim() || null,
        name: document.getElementById('staffName').value.trim(),
        age: parseInt(document.getElementById('staffAge').value),
        idNum: document.getElementById('staffIdNum').value.trim(),
        identityInfo: role,
        vaccinationSiteId: role === 1 ? parseInt(siteId) : null
    };
    
    try {
        UI.showLoading();
        
        await HttpClient.post('/admin/user', data);
        
        UI.showMessage('创建成功', 'success');
        closeModal();
        await loadStaffList();
        
        UI.hideLoading();
    } catch (error) {
        console.error('创建失败:', error);
        UI.hideLoading();
        UI.showMessage('创建失败: ' + error.message, 'danger');
    }
}

/**
 * 显示重置密码模态框
 */
function showResetPasswordModal(staffId, account) {
    document.getElementById('resetStaffId').value = staffId;
    document.getElementById('newPassword').value = '';
    document.getElementById('resetPasswordModal').classList.add('show');
}

/**
 * 关闭重置密码模态框
 */
function closeResetPasswordModal() {
    document.getElementById('resetPasswordModal').classList.remove('show');
    document.getElementById('resetPasswordForm').reset();
}

/**
 * 处理重置密码
 */
async function handleResetPassword() {
    const form = document.getElementById('resetPasswordForm');
    
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const staffId = document.getElementById('resetStaffId').value;
    const newPassword = document.getElementById('newPassword').value.trim();
    
    try {
        UI.showLoading();
        
        await HttpClient.put(`/admin/user/${staffId}/reset-password`, { newPassword });
        
        UI.showMessage('密码重置成功', 'success');
        closeResetPasswordModal();
        
        UI.hideLoading();
    } catch (error) {
        console.error('重置密码失败:', error);
        UI.hideLoading();
        UI.showMessage('重置密码失败: ' + error.message, 'danger');
    }
}

/**
 * 处理删除
 */
function handleDelete(staffId, account) {
    UI.confirm(`确定要删除工作人员"${account}"吗？`, async () => {
        try {
            UI.showLoading();
            
            await HttpClient.delete(`/admin/user/${staffId}`);
            
            UI.showMessage('删除成功', 'success');
            await loadStaffList();
            
            UI.hideLoading();
        } catch (error) {
            console.error('删除失败:', error);
            UI.hideLoading();
            UI.showMessage('删除失败: ' + error.message, 'danger');
        }
    });
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

